import { Context, PlainObject } from "egg";
import { Op } from "sequelize";
import helper from "../helper";
import EntityDao from "../dao";
import { DaoService } from "../mvc";

export default class DeviceService extends DaoService {
  constructor(ctx: Context) {
    super(ctx);
    this.dao = new EntityDao(ctx, ctx.model.Device, [
      {
        model: ctx.model.Application,
        as: "app",
        include: [
          {
            model: ctx.model.Platform,
            as: "platform"
          }
        ]
      }
    ]);
  }

  /**
   * 添加设备
   * @param data
   * @returns
   */
  async create(data: any) {
    return await this.dao.create(data, ["appId", "deviceName", "deviceProtocol", "deviceIp", "devicePort", "deviceAccount", "devicePassword"]);
  }

  /**
   * 删除设备
   * @param deviceId 设备Id
   * @returns
   */
  async destroy(deviceId: string): Promise<ServiceResponse> {
    return await this.dao.destroy(deviceId);
  }

  /**
   * 修改设备
   * @param deviceId
   * @param data
   * @returns
   */
  async update(deviceId: string, data: any): Promise<ServiceResponse> {
    return await this.dao.update(deviceId, data, ["appId", "deviceName", "deviceProtocol", "deviceIp", "devicePort", "deviceAccount", "devicePassword"]);
  }

  /**
   * 查询设备列表
   * @param query ctx.request.query
   * @returns
   */
  async index(query: PlainObject<string>): Promise<ServiceResponse> {
    const where: any = {};
    if (!helper.isEmpty(query.appId)) {
      where.appId = query.appId;
    }
    if (!helper.isEmpty(query.deviceName)) {
      where.deviceName = { [Op.like]: `%${query.deviceName}%` };
    }

    return await this.dao.index(where);
  }

  /**
   * 查询设备明细明细
   * @param deviceId
   * @returns
   */
  async show(deviceId: string): Promise<ServiceResponse> {
    return await this.dao.show(deviceId);
  }

  /**
   * 查询设备分页列表
   * @param query ctx.request.query
   * @returns
   */
  async page(query: PlainObject<string>): Promise<ServiceResponse> {
    const where: any = {};
    if (!helper.isEmpty(query.appId)) {
      where.appId = query.appId;
    }
    if (!helper.isEmpty(query.deviceName)) {
      where.deviceName = { [Op.like]: `%${query.deviceName}%` };
    }
    return await this.dao.page({ current: query.current, pageSize: query.pageSize, where });
  }
}
